<?php
namespace app\common\helper;

// 引入鉴权类
use Exception;
use Qiniu\Auth;
// 引入上传类
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

class Uploader {

    private $_accessKey;
    private $_secretKey;
    private $_bucket;
    private $_domain;
    private $_base64RequestUrl;

    public function __construct() {
        $this->_accessKey = config('Qiniuyun_conf.AccessKey');
        $this->_secretKey = config('Qiniuyun_conf.SecretKey');
        $this->_bucket = config('Qiniuyun_conf.Bucket');
        $this->_domain = config('Qiniuyun_conf.Domain');
        $this->_base64RequestUrl = config('Qiniuyun_conf.Base64UploadUrl');
    }
    // +----------------------------------------------------------------------
    // | 七牛云配置
    // +----------------------------------------------------------------------
    /*private $_config = [
        'AccessKey' => '4LgrCJNWFODg14C7Lbalne98eVTYSMwJXACObjX9',//你的accessKey
        'SecretKey' => 'z2WRHFzO7uZZLbzyTwrLzIiK6FW7ggEgjlugxsMm',//你的secretKey
        'Bucket' => 'crm-images',//上传的空间
        'Domain'=>'http://images.xiaowaimedia.com/',//空间绑定的域名
        'Base64UploadUrl' => 'http://upload.qiniup.com/putb64/-1/', // base64上传的url
    ];*/

    /**
     * 本地图片上传七牛云
     * @return string
     * @throws Exception
     */
    public function uploadQiniu($img)
    {
        vendor('qiniu-php-sdk.autoload');
        $filePath = $img;
        //var_dump($img);die;
        // 上传到七牛后保存的文件名
        $key = substr(md5($img), 0, 5) . date('YmdHis') . rand(0, 9999) . '.jpeg';
        //require_once ROOT_PATH . 'vendor/qiniu-php-sdk-7.2.6/autoload.php';
        // 需要填写你的 Access Key 和 Secret Key
        // 构建鉴权对象
        $auth = new Auth($this->_accessKey, $this->_secretKey);
        // 要上传的空间

        $token = $auth->uploadToken($this->_bucket);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, "image/" . $key, $filePath);
        if ($err !== null) {
            return false;
        } else {
            //返回图片的完整URL
            $url = $this->_domain . $ret['key'];
            // 销毁临时文件
            unlink($filePath);
            return $url;
        }
    }

    /**
     * 上传音乐到七牛云
     *
     * @param $fileName
     * @return bool|string
     * @throws Exception
     */
    public function uploadMusic($fileName)
    {
        vendor('qiniu-php-sdk.autoload');
        $filePath = $fileName;
        //var_dump($img);die;
        // 上传到七牛后保存的文件名
        $key = substr(md5($fileName), 0, 5) . date('YmdHis') . rand(0, 9999);
        //require_once ROOT_PATH . 'vendor/qiniu-php-sdk-7.2.6/autoload.php';
        // 需要填写你的 Access Key 和 Secret Key
        // 构建鉴权对象
        $auth = new Auth($this->_accessKey, $this->_secretKey);
        // 要上传的空间

        $token = $auth->uploadToken($this->_bucket);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, "music/" . $key, $filePath);
        if ($err !== null) {
            return false;
        } else {
            //返回图片的完整URL
            $url = $this->_domain . $ret['key'];
            // 销毁临时文件
            unlink($filePath);
            return $url;
        }
    }


    public function request_by_curl($remote_server, $post_string, $upToken)
    {
        header('Access-Control-Allow-Origin:*');
        $headers = array();
        $headers[] = 'Content-Type:image/jpeg';
        $headers[] = 'Authorization:UpToken ' . $upToken;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        //curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }

    /**
     * base64字符串直接上传
     *
     * @param $base64
     * @param null $key
     * @return bool|string
     */
    function uploadBase64($base64, $key = null)
    {
        vendor('qiniu-php-sdk.autoload');

        $auth = new Auth($this->_accessKey, $this->_secretKey);
        $upToken = $auth->uploadToken($this->_bucket, $key, 3600);//获取上传所需的token

        $pattern = '/data:image\/[\w]*?;base64,/';
        $base = preg_replace($pattern, '', $base64);

        if ($key) {
            $key = \Qiniu\base64_urlSafeEncode($key);
        } else {
            $key = uniqid('photo_album_blessing');
        }
        $ret = $this->request_by_curl($this->_base64RequestUrl .$key, $base, $upToken);
        $ret = json_decode($ret, true);

        if ($ret && empty($ret['error'])) {
            return $this->_domain . $ret['key'];  //可以访问的图片远程地址
        } else {
            return false;
        }
    }

    /**
     * 远程图片直接上传七牛
     *
     * @param $filePath
     * @param $key
     * @return bool
     */
    public function uploadFromRemote($filePath, $key = null){ // 保存的文件名
        vendor('qiniu-php-sdk.autoload');
        // 需要填写你的 Access Key 和 Secret Key
        // 构建鉴权对象
        $auth = new Auth($this->_accessKey, $this->_secretKey);
        // 生成上传 Token
        //$token = $auth->uploadToken(self::BUCKET);
        // 要上传文件的本地路径
        // 上传到七牛后保存的文件名
        if (!$key) {
            $key = time() . '_' . $this->getFilename($filePath);
        }

        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new BucketManager($auth);
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->fetch($filePath, $this->_bucket, $key);
        if ($err !== null) {
            return false;
        } else {
            return $this->_domain . $ret['key'];
        }
    }

    public function getExtension($fileName){
        $pathinfo = pathinfo($fileName);
        return $pathinfo['extension'];
    }

    public function getFilename($fileName){
        return pathinfo($fileName, PATHINFO_BASENAME);
    }
}